const http=require('http');
const url=require('url');
const path=require('path');
const fs=require('fs');

const buffer_split=require(path.resolve(__dirname, './libs/buffer_split'));


const server=http.createServer((req, res)=>{
	let origin=req.headers['origin'];
	if(origin==='null' || origin.startsWith('http://127.0.0.1:8848')) {
		res.setHeader("Access-Control-Allow-Origin", origin);
		res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		res.setHeader("Access-Control-Max-Age", "3600");
		res.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token, Content-Type"); //这里要加上content-type 
		res.setHeader("Access-Control-Allow-Credentials", "true");
	}
	// 分隔符
	let str = '--'+req.headers['content-type'].split('; ')[1].split('=')[1];
	const {pathname, query: get}=url.parse(req.url, true);
	let arr=[];
	let post={};
	let files_key=[];
	
	req.on('data', buffer=>{
		arr.push(buffer);
	});
	
	req.on('end', _=>{
		let result=buffer_split(Buffer.concat(arr), str);
		// 去掉 res 第一个和最后一个元素
		result.pop();
		result.shift();
		result=result.map(item=>item.slice(2, item.length-2));
		result.forEach(item=>{
			let index=item.indexOf('\r\n\r\n');
			let key=item.slice(0, index).toString();
			let value=item.slice(index+4);
			
			if(key.indexOf('\r\n')!==-1) {
				// 文件post数据
				// key 都是 string 类型, 可以直接处理了
				let filename = key.split('\r\n')[0].split('; ')[2].split('=')[1];
				filename = filename.slice(1, filename.length-1);
				files_key.push(filename);
				// 将文件的内容直接写入 upload 文件夹中 
				fs.writeFile(path.resolve(__dirname, `./upload/${filename}`), value, err=>{
					if(err) {
						console.log('写入失败', err.message);
					} else {
						console.log('写入成功');
					}
				});
			} else {
				// 普通post数据
				post[key.toString().split('; ')[1].split('=')[1]]=value.toString();
			} 
		});
		console.log('get', get);
		console.log('post', post);
		console.log('files_key', files_key); 
		res.write('ok');
		res.end();
	});
	
});
server.listen(3000, ()=>{
	console.log('server running success at http://localhost:3000');
});